﻿namespace Ngs.Collections
{
    using System;
    using System.Collections.Generic;

    public class ObserverCollection<T> : ProxyCollection<T>
    {
        public event EventHandler<ItemEventArgs<T>> Added;
        public event EventHandler<ItemEventArgs<T>> Removed;

        public ObserverCollection()
            : this(null)
        {
        }

        public ObserverCollection(IEnumerable<T> collection)
            : base(collection)
        {
        }

        private void RaiseEvent(EventHandler<ItemEventArgs<T>> eventHandler, T item)
        {
            EventHandler<ItemEventArgs<T>> handler = eventHandler;
            if (handler != null)
            {
                handler(this, new ItemEventArgs<T>(item));
            }
        }

        protected override void OnAdd(T item)
        {
            RaiseEvent(this.Added, item);
        }

        protected override void OnRemove(T item)
        {
            RaiseEvent(this.Removed, item);
        }


        public static void AddEvents(ObserverCollection<T> collection, EventHandler<ItemEventArgs<T>> onItemAdded)
        {
            collection.Added += new EventHandler<ItemEventArgs<T>>(onItemAdded);
        }

        public static void ClearEvents(ObserverCollection<T> collection, EventHandler<ItemEventArgs<T>> onItemAdded)
        {
            collection.Added -= new EventHandler<ItemEventArgs<T>>(onItemAdded);
        }
    }
}
